package org.example.wx.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import org.example.wx.Node.Interface.ServiceRegister;
import org.example.wx.Node.ZooKeeperServer;
import org.example.wx.netty.Handler.RPCServerHandler;

public class NettyRPCServerBootStrap {

    private final Integer port;

    private final EventLoopGroup bossLoopGroup;

    private final EventLoopGroup workerLoopGroup;

    private final ServiceRegister serviceRegister;

    //port是启动的服务的接口,也就是netty监听的地址。
    public NettyRPCServerBootStrap(Integer port) {
        this.port = port;
        serviceRegister = new ZooKeeperServer(port);
        bossLoopGroup = new NioEventLoopGroup();
        workerLoopGroup = new NioEventLoopGroup();
    }

    public void start() throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
            serverBootstrap.group(bossLoopGroup, workerLoopGroup).channel(NioServerSocketChannel.class).localAddress(port).
                    childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
//                            pipeline.addLast(new RPCServerHandler());
                            pipeline.addLast(new LineBasedFrameDecoder(1024 * 1024))
                                    .addLast(new RPCServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            workerLoopGroup.shutdownGracefully().sync();
            bossLoopGroup.shutdownGracefully().sync();
        }
    }

}
